<?php

namespace app\db\controller;

use think\Cache;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 病例用户相关接口
 * @author MSQ 2021-8-5
 * MSG提示:DB03000-DB03020
 */
class DbUser extends Common
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['getUserList'];
    protected $layout = '';
    protected $pageSum = 10;

    public function _initialize()
    {
        parent::_initialize();
        //设置过滤方法
        $this->request->filter(['trim']);
    }

    /**
     * 添加用户
     * @author MSQ 2021-8-5
     */
    public function addCaseUser()
    {
        $usercare_id = $this->auth->getUsercareinfo('id');

        $database_id     = $_POST['database_id'];// 数据库id
        $user_name       = $_POST['user_name'];// 用户姓名
        $id_card_no      = $_POST['id_card_no'];// 身份证号
        $hospital_number = $_POST['hospital_number'];// 住院号
        $master_db_id    = $_POST['master_db_id'];// 总库id
        $user_sex        = $_POST['user_sex'];// 性别 0保密 1男 2女
        $user_birthday   = $_POST['user_birthday'];// 出生日期
        $user_age        = $_POST['user_age'];// 年龄

        if (!$user_name) $this->error('DB03001:请输入姓名');

        $databaseInfo = model('DbDatabase')->getDetails($master_db_id);
        if (!$databaseInfo || $databaseInfo['parent_id']) $this->error('DB03002:数据库错误');

        # 验证身份证号
        $checkIdCard = true;
        if ($id_card_no) $checkIdCard = isIDCardNo($id_card_no);
        if (!$checkIdCard) $this->error('DB03003:身份证号错误');

        if ($hospital_number){
            if(strpos($hospital_number,'P') !== false || strpos($hospital_number,'p') !== false){
                $hospital_number = 'P'.substr($hospital_number,1);
            }elseif (strpos($hospital_number,'G') !== false || strpos($hospital_number,'g') !== false){
                $hospital_number = 'G'.substr($hospital_number,1);
            }elseif (strpos($hospital_number,'F') !== false || strpos($hospital_number,'f') !== false){
                $hospital_number = 'F'.substr($hospital_number,1);
            }
        }
        # 检测用户是否已存在 身份证 OR 住院号
        $user_id = model('DbUser')->getUserIdByIDCardOrHospitalNumber($master_db_id,$id_card_no,$hospital_number);

        # 存在用户 检测子库是否已复制
        if ($user_id && ($database_id != $master_db_id)) {
            $copyInfo = model('DbUserRelationDbChild')->getCopyUsers($database_id,$user_id,'user_id');
            if ($copyInfo) $this->success('病例已存在');
            # 病例存在总库但不在子库，复制到子库
            $copy_users[] = [
                'user_id'     => $user_id,
                'user_number' => $user_number
            ];
            $copyRes = model('DbUserRelationDbChild')->copyUserToChildDb($master_db_id,[$database_id],$copy_users,$usercare_id);
            if (!$copyRes) $this->error('DB03004:操作失败');

            $this->success('病例复制到子库成功');
        }elseif ($user_id) {
            $this->success('病例已存在');
        }
        $data = $_POST;
        $data['usercare_id']    = $usercare_id;
        $data['id_card_number'] = $id_card_no;

        Db::startTrans();
        $addRes = model('DbUser')->createCaseUser($data);
        if (!$addRes) {
            Db::rollback();
            $this->error('DB03004:创建失败');
        }
        Db::commit();

        $this->success('创建成功');
    }
    /**
     * 获取数据库病例列表
     * @author MSQ 2021-8-6
     */
    public function getUserList()
    {
        $database_id = $_POST['database_id'];// 数据库id
        $search      = $_POST['search'];// 搜索内容
        $page['idx'] = $_POST['page'] ? $_POST['page'] : 1;// 页数
        $page['sum'] = $_POST['page_sum'] ? $_POST['page_sum'] : $this->pageSum;// 每页条数
        $order_sort  = $_POST['order_sort'] ? $_POST['order_sort'] : 'DESC';// 排序
        $usercare_id = $this->auth->getUsercareinfo('id');

        if (!$database_id || !$usercare_id) $this->error('DB03005:参数错误');

        $databaseInfo = model('DbDatabase')->getDetails($database_id);
        if (!$databaseInfo) $this->error('DB03006:数据库不存在');

        # 当前医务是否加入数据库
        $isJoin = model('DbUsercareRelation')->getJoinInfoByDbIds($usercare_id,$database_id,'id');
        if (!$isJoin) $this->error('DB03007:暂未加入该库，不允许查看');

        # 更新当前数据库权限
        $auths = model('DbUsercareRelation')->getJoinDbAuth($usercare_id,$database_id);
        session('_database_id',$database_id);
        $param['database_info'] = $databaseInfo;
        $param['search']        = $search;
        $param['page']          = $page;
        $param['order_sort']    = $order_sort;
        $userList = model('DbUser')->getDatabaseUserList($param);

        $returnData = [
            'database_info' => $databaseInfo,
            'auths'         => $auths,
            'list'          => $userList['list'],
            'total'         => $userList['total'],
        ];
        $this->success('获取成功',$returnData);
    }
    /**
     * 复制病例到子库
     * @author MSQ 2021-8-7
     */
    public function copyUser()
    {
        $origin_user = $_POST['origin_user']; //选择复制用户
        $target_db   = $_POST['target_db'];   //拷贝的目标库-子库
        $database_id = $_POST['database_id']; //拷贝的来源库
        $copy_type   = $_POST['copy_type'];   // 复制类型 1部分复制 2全部复制
        $search      = $_POST['search'];      //搜索内容
        $usercare_id = $this->auth->getUsercareinfo('id');

        if (!$target_db || !$database_id || !$copy_type) $this->error('DB03008:缺少数据库参数');
        if (!$copy_type || ($copy_type == 1 && !$origin_user)) $this->error('DB03009:参数错误');

        # 来源数据库是否是总库
        // $databasePid = model('DbDatabase')->getDetails($database_id,'parent_id');
        // if ($databasePid) $this->error('DB03010:来源数据库非法');

        $databaseInfo = model('DbDatabase')->getDetails($database_id);
        if (!$databaseInfo) $this->error('DB03010:来源数据库非法');
        
        if ($copy_type == 2 && !$origin_user) {
            # 全部复制 读取来源库所有用户
            // $origin_user = model('DbUser')->getParDbAllUserList($database_id,$search,'id as user_id,user_number');
            $origin_user = model('DbUser')->getAllDbUserList($database_id,$databaseInfo['parent_id'],$search,'u.id as user_id,u.user_number');
        }
        if (!$origin_user) $this->error('DB03011:没有复制病例信息');

        Db::startTrans();
        # 复制到子库
        $copyRes = model('DbUserRelationDbChild')->copyUserToChildDb($database_id,$target_db,$origin_user,$usercare_id);

        if (!$copyRes) {
            Db::rollback();
            $this->error('DB03012:复制失败');
        }
        Db::commit();
        $this->success('复制成功');
    }
    /**
     * 删除用户
     * @author MSQ 2021-8-7
     */
    public function deleteUser()
    {
        $database_id  = $_POST['database_id']; //数据库id
        $delUserIds   = $_POST['delete_users']; //删除的用户Id

        if (!$database_id || !$delUserIds) $this->error('DB03013:参数错误');

        Db::startTrans();
        # 删除用户
        $delRes = model('DbUser')->deleteUserLogic($database_id,$delUserIds);
        if (!$delRes) {
            Db::rollback();
            $this->error('DB03014:删除失败');
        }
        Db::commit();
        $this->success('删除成功');
    }
    /**
     * 获取病例详情
     * @author MSQ 2021-8-17
     */
    public function getDetails()
    {
        $database_id  = $_POST['database_id']; //数据库id
        $template_id  = $_POST['template_id']; //模板id
        $item_id      = $_POST['item_id']; //目录id
        $user_id      = $_POST['user_id']; //用户id
        if (!$database_id || !$template_id || !$item_id || !$user_id) $this->error('DB03015:参数错误');
        $returnData = [];
        # 优先读取缓存里的变量列表
        $need = ['need_question','need_option','need_data'];
        $cacheKey = model('DbTemplateRelationQuestion')->getQuestionListCacheKey($template_id,$item_id,$need);
        $questionList = Cache::get($cacheKey);
        if (!$questionList) {
            $questionList = model('DbTemplateRelationItem')->getTemplateItemQuestionList($template_id,$item_id,$need);
        }
        if (!$questionList) $this->success('获取成功',$returnData);

        # 所有二级模块
        $itemIdList = [];
        foreach ($questionList as $key => $value) {
            # 循环一级模块，获取每个二级模块的item_id列表
            if (@$value['second_item']) {//正常一定会有二级模块
                $itemIdList = array_merge($itemIdList,array_column($value['second_item'], 'item_id'));
            }
        }
        $itemRelationDataList = model('DbItemRelationData')->getListByUserAndItemId($user_id,$itemIdList,'','weight DESC,id ASC');
        if (!$itemRelationDataList) $this->success('获取成功',$questionList);

        $itemRelationDataIds = array_column($itemRelationDataList, 'id');

        # 初始化关联模块的数组
        $itemRelationDataArr = [];
        # 初始化答案数组
        $answerDataList = [];
        # 初始化回答
        $initAnswerDataArr = [
            'db_data_id'   => [],
            'answer_value' => [],
        ];
        # 初始化回答
        $initAnswerDataStr = [
            'db_data_id'   => 0,
            'answer_value' => '',
        ];
        foreach ($itemRelationDataList as $k_ir => $v_ir) {
            $itemRelationDataArr[$v_ir['item_id']][$v_ir['id']] = $v_ir;
        }
        $answerDataLists = model('DbData')->getListsByItemRelationDataId($itemRelationDataIds);
        foreach ($answerDataLists as $k_answer => $v_answer) {
            $answerDataList[$v_answer['item_relation_data_id']][$v_answer['question_id']][] = $v_answer;
        }
        foreach ($questionList as $k_i => $v_i) {
            if (!@$v_i['second_item']) continue;
            
            # 循环一级模块
            foreach ($v_i['second_item'] as $k_i_c => $v_i_c) {
                # 循环二级模块
                if (!isset($itemRelationDataArr[$v_i_c['item_id']])) continue;
                
                # 循环item_relation_data_id
                foreach ($itemRelationDataArr[$v_i_c['item_id']] as $k_i_c_r => $v_i_c_r) {
                    # 将答案放进问题列表
                    $questionAnswerData = $v_i_c_r;
                    foreach ($v_i_c['question_lists'] as $k_q => $v_q) {
                        if (isset($v_q['child_question']) && $v_q['child_question']) {
                            # 变量组，有二级变量
                            # 二级变量接收数组
                            $secondQuestion = [];
                            # 初始化二级变量接收数组的key
                            $sort = 0;
                            foreach ($v_q['child_question'] as $k_q_c => $v_q_c) {
                                # 接收值并将答案和是否漏填答案对应即可
                                //文件类型的题目
                                // if ($v_q_c['question_type'] == 4) $v_q_c['img_host'] = get_img_host();
                                $selfQuestionData = @$answerDataList[$v_i_c_r['id']][$v_q_c['question_id']];
                                $secondQuestion[$sort] = $v_q_c;
                                # 初始化回答
                                $secondQuestion[$sort]['answer_data'] = $initAnswerDataStr;
                                # 单选/多选默认为数组
                                if (in_array($v_q_c['question_type'],[1,2])) $secondQuestion[$sort]['answer_data'] = $initAnswerDataArr;

                                if ($selfQuestionData) {
                                    # 对应变量有答案
                                    /*if ($v_q_c['question_type'] == 4) {
                                        foreach ($selfQuestionData as $k_file => $v_file) {
                                            # 循环处理图片
                                            $selfQuestionData[$k_file]['answer_data'] = explode(',', $v_file['answer_data']);
                                        }
                                    }*/
                                    $answerValueData = [];
                                    if (in_array($v_q_c['question_type'],[1,2])){
                                        # 单选/多选循环处理回答db_data_id与answer_value是数组
                                        foreach ($selfQuestionData as $k_data => $v_data) {
                                            $answerValue = $v_data['answer_value'];
                                            if ($v_data['other_data_value']) $answerValue .= '&=>'.$v_data['other_data_value'];

                                            $answerValueData['db_data_id'][]   = $v_data['id'];
                                            $answerValueData['answer_value'][] = $answerValue;
                                        }
                                    }else{
                                        # 其他类型变量处理回答db_data_id与answer_value是字符串
                                        $answerValueData['db_data_id']   = $selfQuestionData[0]['id'];
                                        $answerValueData['answer_value'] = $selfQuestionData[0]['answer_value'];
                                    }
                                    $secondQuestion[$sort]['answer_data'] = $answerValueData;
                                }
                                $sort++;
                            }
                            $v_q['child_question'] = $secondQuestion;
                        }else{
                            // if ($v_q['question_type'] == 4) $v_q['img_host'] = get_img_host();
                            $selfQuestionData = @$answerDataList[$v_i_c_r['id']][$v_q['question_id']];

                            # 初始化回答
                            # 初始化回答
                            $v_q['answer_data'] = $initAnswerDataStr;
                            # 单选/多选默认为数组
                            if (in_array($v_q['question_type'],[1,2])) $v_q['answer_data'] = $initAnswerDataArr;

                            if ($selfQuestionData) {
                                # 对应变量有答案
                                /*if ($v_q['question_type'] == 4) {
                                    foreach ($selfQuestionData as $k_file => $v_file) {
                                        # 循环处理图片
                                        // $selfQuestionData[$k_file]['answer_data'] = explode(',', $v_file['answer_data']);
                                    }
                                }*/
                                $answerValueData = [];
                                if (in_array($v_q['question_type'],[1,2])){
                                    # 单选/多选循环处理回答db_data_id与answer_value是数组
                                    foreach ($selfQuestionData as $k_data => $v_data) {
                                        $answerValue = $v_data['answer_value'];
                                        if ($v_data['other_data_value']) $answerValue .= '&=>'.$v_data['other_data_value'];

                                        $answerValueData['db_data_id'][]   = $v_data['id'];
                                        $answerValueData['answer_value'][] = $answerValue;
                                    }
                                }else{
                                    # 其他类型变量处理回答db_data_id与answer_value是字符串
                                    $answerValueData['db_data_id']   = $selfQuestionData[0]['id'];
                                    $answerValueData['answer_value'] = $selfQuestionData[0]['answer_value'];
                                }
                                $v_q['answer_data'] = $answerValueData;
                            }
                        }
                        $questionAnswerData['relation_answer'][] = $v_q;
                    }
                    # 将问题-答案对应组放入二级模块下面
                    $questionList[$k_i]['second_item'][$k_i_c]['question_answer_list'][] = $questionAnswerData;
                }
            }
        }
        $this->success('获取成功',$questionList);
    }
    /**
     * 保存病例数据
     * @author MSQ 2021-8-18
     */
    public function saveData()
    {
        $database_id  = $_POST['database_id']; //数据库id
        $master_db_id = $_POST['master_db_id']; //总库id
        $template_id  = $_POST['template_id']; //模板id
        $user_id      = $_POST['user_id']; //用户id
        $item_data    = $_POST['item_data']; //保存的数据
        $item_id      = $_POST['item_id']; //模板id
        $usercare_id  = $this->auth->getUsercareinfo('id');

        if (!$database_id || !$master_db_id || !$template_id || !$user_id) $this->error('DB03016:参数错误');
        if (!$item_data) $this->success('无修改');

        # 日志记录
        $path = './Runtime/Logs/DB/db_save/';
        if (!is_dir($path)) {//没有则先创建填写日志的目录
            mkdir(iconv("UTF-8", "GBK", $path),0777,true);
        }
        $log_path = $path.date("Y-m-d").'.log';
        //记录操作的医生id和所传的参数日志
        file_put_contents($log_path,'date_time:'.date("Y-m-d H:i:s").PHP_EOL.'usercare_id:'.$usercare_id.PHP_EOL.'master_db_id:'.$master_db_id.PHP_EOL.'database_id:'.$database_id.PHP_EOL.'user_id:'.$user_id.PHP_EOL.'item_id:'.$item_id.PHP_EOL.var_export($item_data,true).PHP_EOL.'================='.PHP_EOL,FILE_APPEND);
        Db::startTrans();

        $returnData = model('DbData')->saveDatabaseAnswer($usercare_id,$master_db_id,$user_id,$item_data);
        if (!$returnData) {
            Db::rollback();
            $this->error('DB03017:操作失败');
        }
        Db::commit();
        $this->success('操作成功');

    }
    /**
     * 删除模块关联数据
     * @author MSQ 2021-8-18
     */
    public function deleteItemRelationData()
    {
        $database_id = $_POST['database_id'];
        $template_id = $_POST['template_id'];
        $relationIds = $_POST['relationIds']; //删除的模块关联数据id
        if (!$relationIds) $this->error('DB03018:参数错误');

        Db::startTrans();
        # 修改模块关联数据为删除
        $deleteRes = model('DbItemRelationData')->deleteItemRelationData(['id' => ['IN',$relationIds]]);
        if (!$deleteRes) {
            Db::rollback();
            $this->error('DB03019:操作失败');
        }
        # 修改qt_db_data表为删除
        $deleteDataRes = model('DbData')->deleteDbData(['item_relation_data_id' => ['IN',$relationIds]]);
        if (!$deleteDataRes) {
            Db::rollback();
            $this->error('DB03020:操作失败');
        }

        Db::commit();
        $this->success('操作成功');
    }
    /**
     * 导出病例
     * @author MSQ 2021-8-24
     */
    public function exportUsers()
    {
        $database_id = $_REQUEST['database_id'];
        $template_id = $_REQUEST['template_id'];
        $user_ids    = isset($_REQUEST['user_ids']) ? explode(',',$_REQUEST['user_ids']) : [];
        $search      = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';

        if (!$database_id || !$template_id) $this->error('DB03020:参数错误');

        $databaseInfo = model('DbDatabase')->getDetails($database_id);
        if (!$databaseInfo) $this->error('DB03021:数据库不存在');

        # 未选择导出用户 默认导出数据库所有用户
        if (!$user_ids) {
            $userIds = model('DbUser')->getAllDbUserList($database_id,$databaseInfo['parent_id'],$search,'u.id');
            $user_ids = array_column($userIds,'id');
        }
        if (!$user_ids) $this->error('DB03022:导出病例不能为空');

        $param = [
            'database_id' => $database_id,
            'template_id' => $template_id,
            'userIds'     => $user_ids,
            'usercare_id' => $this->auth->getUsercareinfo('id'),
            'export_name' => '',
            'note'        => '',
        ];

        $res = model('DbExportRecord')->exportUsers($param);
        if (!$res) $this->error('DB03023:导出失败');

        $this->success('操作成功');
    }
    /**
     * 获取库用户信息
     * @author MSQ 2021-10-9
     */
    public function getUserInfo()
    {
        $database_id = $_POST['database_id'];
        $user_id     = $_POST['user_id'];

        if (!$database_id || !$user_id) $this->error('DB03024:参数错误');

        $userInfo = model('DbUser')->getDetails($user_id);
        if (!$userInfo) $this->error('DB03025:用户不存在或已删除');

        $this->success('获取成功',$userInfo);
    }
}
